﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using BLL;
using Model;
using System.Data.SqlClient;

namespace WebPortal.Controllers
{
    public class DQConfigController : BaseController
    {
        //
        // GET: /DQ/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Add(string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DQConfigBLL bll = new DQConfigBLL(loginInfos);
            if (string.IsNullOrEmpty(id))
                return View(new Model.DQRulesConfig());
            else
                return View(bll.GetRoleList(id));
        }
        /// <summary>
        /// 保存DQ信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="tableName"></param>
        /// <param name="dqName"></param>
        /// <param name="dqDesc"></param>
        /// <param name="gridData"></param>
        /// <returns></returns>
        public ActionResult SaveData()
        {
            string id = Request.Params["id"];
            string modelID = Request.Params["modelID"];
            string dqName = Request.Params["dqName"];
            string dqDesc = Request.Params["dqDesc"];
            string gridData = Request.Params["gridData"];
            string dbName = Request.Params["dbName"];
            string nmID = Request.Params["nmID"];
            string ndbName = Request.Params["ndbName"];
            LoginInfo loginInfos = base.loginInfo();

            loginInfos.DBName = dbName;

            ModelConfigBLL mbll = new ModelConfigBLL(loginInfos);
            DQConfigBLL bll = new DQConfigBLL(loginInfos);
            if (bll.DQNameIsExist(dqName, id, modelID))//存在相同名称
            {
                return Json("2");
            }
            ModelConfig model = mbll.GetItem(modelID);
            if (model.AddType == "Reference")
            {
                modelID = model.ParentModelID;
            }

            DQConfigTransData data = new DQConfigTransData();
            data.DQConfig = new DQConfig()
            {
                GUID = id,
                DQ_Name = dqName,
                ModelID = modelID,
                DQ_Description = dqDesc,
                SchemaName = "Fact",
                TableName = "ODS_" + modelID
            };
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            IList<DQRulesConfigTrans> jsonList = (IList<DQRulesConfigTrans>)jsSerializer.Deserialize(gridData, typeof(IList<DQRulesConfigTrans>));
            IList<DQRulesConfig> data1 = new List<DQRulesConfig>();

            ModelConfigBLL modelBll = new ModelConfigBLL(loginInfos);
            IList<ModelViewConfig> mvList = modelBll.GetTableInfo(modelID, "");//取表数据
            foreach (DQRulesConfigTrans item in jsonList)
            {
                string columnName = item.DisplayName;
                foreach (ModelViewConfig modelItem in mvList)
                {
                    string tbColumn = string.Format("[{0}].[{1}]", modelItem.TableName, modelItem.ColumnName);
                    if (columnName.IndexOf(tbColumn) > -1)
                    {
                        string nColumnName = string.Format("[{0}{1}]", modelItem.ColumnSourceID.Replace("-", ""), modelItem.ColumnName);
                        columnName = columnName.Replace(tbColumn, nColumnName);
                    }
                }
                data1.Add(new DQRulesConfig()
                {
                    ColumnName = columnName,
                    DisplayName = item.DisplayName,
                    ColumnDesc = item.ColumnDesc,
                    LegalOperator = item.LegalType == "合法规则" ? item.Operator : "",
                    LegalRules = item.LegalType == "合法规则" ? item.Rules : "",
                    ILegalOperator = item.LegalType == "非法规则" ? item.Operator : "",
                    IllegalRules = item.LegalType == "非法规则" ? item.Rules : "",
                    UniqueConstraint = item.UniqueConstraint == "1" ? 1 : 0
                });
            }
            data.DQRulesConfigList = data1;
            return Json(bll.Update(data));
        }

        public ActionResult Edit(string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            string nmID = Request.Params["nmID"];
            string ndbName = Request.Params["ndbName"];
            if (!string.IsNullOrEmpty(nmID))//发送到实例页面请求 
            {
                loginInfos.DBName = ndbName;
            }
            DQConfigBLL bll = new DQConfigBLL(loginInfos);
            if (string.IsNullOrEmpty(id))
                return View(new Model.DQConfig());
            else
                return View(bll.GetItem(id));
        }
        /// <summary>
        /// 下一步
        /// </summary>
        /// <param name="modelID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult UpStep(string modelID, string dbName)
        {
            string date = Request.Params["data"];
            string nmID = Request.Params["nmID"];
            string ndbName = Request.Params["ndbName"];
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            IList<DQConfig> jsonList = (IList<DQConfig>)jsSerializer.Deserialize(date, typeof(IList<DQConfig>));

            LoginInfo loginInfos = base.loginInfo();
            if (string.IsNullOrEmpty(nmID))
                loginInfos.DBName = dbName;
            else
            {
                loginInfos.DBName = ndbName;
                modelID = nmID;
            }
            DQConfigBLL bll = new DQConfigBLL(loginInfos);
            try
            {
                string dq_Col = bll.CheckDQColumn(modelID);//检查dq中是否有字段引用不存在的表。
                if (dq_Col == "1")
                {
                    if (bll.UpStep(jsonList, modelID))
                    {
                        return Json("1");
                    }
                    else
                        return Json("操作失败！");
                }
                else
                    return Json("操作失败！数据质量：" + dq_Col+" 引用了不存在的表，请检查配置。");
            }
            catch (Exception ex) { return Json(ex.Message); }
        }
        /// <summary>
        /// 查询DQConfig表集合
        /// </summary>
        /// <param name="keyWords">选择的表</param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public ActionResult GetList()
        {
            string modelID = Request.Params["modelID"];
            string dbName = Request.Params["dbName"];
            string sortNum = Request.Params["SortNum"];

            string order = Request.Params["order"];
            string sort = Request.Params["sort"];
            if (string.IsNullOrEmpty(sort))
            {
                sort = "SortNum";
                order = "asc";
            }
            if (string.IsNullOrEmpty(order))
                order = "asc";

            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;

            string nmID = Request.Params["nmID"];
            string ndbName = Request.Params["ndbName"];
            if (!string.IsNullOrEmpty(nmID))//发送到实例页面请求 
            {
                loginInfos.DBName = ndbName;
                modelID = nmID;
            }

            DQConfigBLL bll = new DQConfigBLL(loginInfos);
            ModelConfigBLL mbll = new ModelConfigBLL(loginInfos);
            ModelConfig model = mbll.GetItem(modelID);
            if (model.AddType == "Reference")
            {
                modelID = model.ParentModelID;
            }
            SqlParameter[] pare = new SqlParameter[]{
            new SqlParameter("@ModelID",modelID) 
            };
            IList<DQConfig> list = bll.GetList(pare, sort, order);

            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", list.Count);
            jsonDict.Add("rows", list);

            return Json(jsonDict);
        }

        public ActionResult GetOperatorList()
        {
            return Json(OperatorBLL.GetList());
        }
        /// <summary>
        /// 取表字段列表
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="dqid">DQ表ID</param>
        /// <returns></returns>
        public ActionResult GetFactTableColumns(string modelID, string dqid, string dbName)
        {
            IList<DQRulesConfigTrans> result = new List<DQRulesConfigTrans>();

            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;

            DQRulesConfigBLL rbll = new DQRulesConfigBLL(loginInfos);
            IList<DQRulesConfig> dbList = rbll.GetListByDQID(dqid);
            foreach (DQRulesConfig model in dbList)
            {
                DQRulesConfigTrans item = new DQRulesConfigTrans();
                item.GUID = model.GUID;
                item.DisplayName = model.DisplayName;
                item.ColumnName = model.ColumnName;
                item.ColumnDesc = model.ColumnDesc;
                item.UniqueConstraint = model.UniqueConstraint.ToString();
                item.LegalType = string.IsNullOrEmpty(model.LegalOperator) ? "非法规则" : "合法规则";
                item.Operator = string.IsNullOrEmpty(model.LegalOperator) ? model.ILegalOperator : model.LegalOperator;
                item.Rules = string.IsNullOrEmpty(model.LegalRules) ? model.IllegalRules : model.LegalRules;
                result.Add(item);
            }
            Dictionary<String, Object> jsonDict = new Dictionary<String, Object>();
            jsonDict.Add("total", result.Count);
            jsonDict.Add("rows", result);
            return Json(jsonDict);
        }

        //--------------------------
        /// <summary>
        /// 查询ODS表集合
        /// </summary>
        /// <returns></returns>
        public ActionResult GetFactTableList(string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            FactTableBLL bll = new FactTableBLL(loginInfos);
            IList<FactTable> data = bll.GetList();
            return Json(data);
        }

        /// <summary>
        /// 删除DQConfig表中的单条记录
        /// </summary>
        /// <param name="id">主键ID</param>
        public ActionResult Delete(string id, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DQConfigBLL bll = new DQConfigBLL(loginInfos);
            try
            {
                return Json(bll.Delete(id));
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }

        public int GetDQConfigCount(string tableName, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            DQConfigBLL bll = new DQConfigBLL(loginInfos);
            return bll.GetDQConfigCount(tableName) + 1;
        }

        public string ReplaceColumn(string value, string dbName)
        {
            return value.Replace("|!@#$%^&*|", "");
        }
    }
}
